package service

import (
	"ant-agent/exec/model"
	"ant-agent/pkg/logger"
	"encoding/json"
	"fmt"
	"os"
	"sync"
)

// ==========================
// 任务状态结构与管理器
// ==========================

type TaskStatus struct {
	JobId          string                       `json:"job_id"`
	ExecCode       string                       `json:"exec_code"`
	OperationType  string                       `json:"operation_type"`
	JobStatus      string                       `json:"job_status"`
	CurrentStep    int                          `json:"current_step"`
	Tag            string                       `json:"tag"`
	UsageType      string                       `json:"usage_type"`
	IP             string                       `json:"ip"`
	SubJobs        map[int]*model.SubJob        `json:"sub_jobs"` // key=step_num
	InputParams    []model.JobParams            `json:"input_params"`
	OutputParams   []model.JobOutputParams      `json:"output_params"`
	CancelChan     chan bool                    `json:"-"` // 用于中止任务的通道
	ManualStepChan chan model.TaskResumeRequest `json:"-"` // 用于人工处理步骤的通道
}

var TaskManager = struct {
	sync.RWMutex
	Tasks map[string]*TaskStatus // key=jobId
}{
	Tasks: make(map[string]*TaskStatus),
}

func GetJobStatus(jobId string) (*TaskStatus, error) {
	TaskManager.RLock()
	status, ok := TaskManager.Tasks[jobId]
	TaskManager.RUnlock()
	if !ok {
		resultPath := fmt.Sprintf("%s/jobId_%s/result.json", JobsBaseDir, jobId)
		data, err := os.ReadFile(resultPath)
		if err != nil {
			return nil, fmt.Errorf("找不到任务的状态信息: jobId=%s", jobId)
		}
		var recovered TaskStatus
		if err := json.Unmarshal(data, &recovered); err != nil {
			return nil, fmt.Errorf("解析任务状态文件失败: %s", err.Error())
		}
		logger.Debug("获取到任务状态信息: jobId=%s ", jobId)
		return &recovered, nil
	}
	if isJobRunning(status.JobStatus) {
		writeResultToFile(fmt.Sprintf("%s/jobId_%s/result.json", JobsBaseDir, jobId), status)
	}
	return status, nil
}

func isJobRunning(jobStatus string) bool {
	return jobStatus == model.JobRunning || jobStatus == model.JobNotRun
}

func ResumeManualJob(resumeReq *model.TaskResumeRequest) error {
	TaskManager.RLock()
	taskStatus, exists := TaskManager.Tasks[resumeReq.JobId]
	TaskManager.RUnlock()

	if !exists {
		return fmt.Errorf("任务 %s 不存在", resumeReq.JobId)
	}

	if taskStatus.JobStatus != model.JobProcessing {
		return fmt.Errorf("任务 %s 不处于待处理状态", resumeReq.JobId)
	}

	select {
	case taskStatus.ManualStepChan <- *resumeReq:
		logger.Info("已发送恢复信号到任务 %s, 操作: %s", resumeReq.JobId, resumeReq.Action)
		return nil
	default:
		return fmt.Errorf("无法发送恢复信号到任务 %s, 通道已满或已关闭", resumeReq.JobId)
	}
}
